# -*- coding: utf-8 -*-
# 定时任务
import tushare as ts
import logging
import os
import time
import urllib
import random
from sqlalchemy import create_engine
from djangoProject import settings
from gplucky.models import *
import requests

logger = logging.getLogger("django")
api = ts.pro_api(settings.TUSHARE_TOKEN)

class trading(object):

    # BAR数据
    def bar(self, code, start, end):
        print(ts.bar(code, start_date=start, end_date=end, conn=ts.get_apis(), ma=[5, 10, 20, 30, 50, 90, 120],
                     factors=['vr', 'tor']))

    # 获取k线数据
    def get_k_data(self):
        print(ts.get_k_data('600009', start='2018-04-24', end='2018-04-25'))


    # 一次性获取最近一个日交易日所有股票的交易数据
    def get_today_all(self):
        print(ts.get_today_all())


    # 获取每日收盘行情
    def get_day_all(self):
        print(ts.get_day_all())


    # bar('600009', '2017-06-01', '2018-04-24')

    # 获取大盘上证指数行情
    def get_index(self):
        print(ts.get_index().head(1))


    # 大单交易数据
    def get_sina_dd(self, code, date, volume):
        df = ts.get_sina_dd(code, date, vol=int(volume), pause=0.05)
        if df is None:
            return None
        return df.to_json(orient='records')


    # 获取当日分笔明细数据  无代理
    def get_today_ticks(self, code):
        try:
            return ts.get_today_ticks(code, pause=1).to_json(orient='records')
        except Exception as er:
            print(er)


    # 获取当日分笔明细数据  有代理
    def get_today_ticks_proxy(self, code, proxy):
        try:
            os.environ['http_proxy'] = 'http://' + proxy
            print(os.environ.get('http_proxy'))
            return ts.get_today_ticks(code, pause=1).to_json(orient='records')
        except Exception as er:
            print(er)

    # 获取历史分笔（根据天来，并存储到数据库中）
    @classmethod
    def init_tick_data_by_date(cls, date, isCallback):
        blackList = settings.rds.smembers("BLACK_LIST");
        blArry = []
        for i, var in enumerate(list(blackList)):
            blArry.append(str(var, encoding="utf-8"))

        stock_list = StockBasic.objects.exclude(ts_code__in=blArry);

        GetTickData.objects.filter(date=date).delete()

        engine = create_engine(settings.MYSQL_ENGINE_URL)
        for i, var in enumerate(stock_list):
            try:
                df = ts.get_tick_data(var.symbol, date=date,src='tt')
                if df is None:
                    continue
                if df.empty:
                    continue
                df = df.rename(index=str, columns={"change": "change_price"})
                df['code'] = var.symbol
                df['date'] = date
                df.to_sql('get_tick_data', engine, if_exists='append', index=False)
                logger.info("init_tick_data_by_date [%s][%s][%s/%s]" % (date, var.symbol, (i+1), stock_list.count()))
            except Exception as e:
                    logger.error("init_tick_data_by_date error, code=[%s], error=[%s]",var.symbol, e)
                    continue
        if isCallback == "true":
            # requests.get("http://localhost:8083/ts/calculateDailyTick?date=" + date)
            requests.get("http://106.14.174.204:8083/ts/calculateDailyTick?date=" + date)

    # 获取历史分笔（code、date,并村塾到数据库中）
    @classmethod
    def sync_tick_data_by_code_date(cls, date, code):
        list = GetTickData.objects.filter(date=date, code=code)
        if len(list) > 0 :
            logger.info("sync_tick_data_by_code_date exist! date=[%s], code=[%s]", date, code)
            return
        try:
            engine = create_engine(settings.MYSQL_ENGINE_URL)
            df = ts.get_tick_data(code, date=date, src='tt')
            if df is None:
                logger.error("sync_tick_data_by_code_date df is None! date=[%s], code=[%s] exist!", date, code)
                return
            if df.empty:
                logger.error("sync_tick_data_by_code_date df is Empty! date=[%s], code=[%s] exist!", date, code)
                return
            df = df.rename(index=str, columns={"change": "change_price"})
            df['code'] = code
            df['date'] = date
            df.to_sql('get_tick_data', engine, if_exists='append', index=False)
            logger.info("sync_tick_data_by_code_date success! [%s][%s]" % (date, code))
        except Exception as e:
            logger.error("sync_tick_data_by_code_date error, code=[%s], error=[%s]", code, e)